class Community < ActiveRecord::Base
  has_many :users
  belongs_to :district
  has_many :common_posts
  
  #belongs_to :created_user, :class_name => "User", :foreign_key => "created_user_id"
  
  has_one :community_forum
  
  #has_and_belongs_to_many :sites
  has_many :community_sites, :dependent => :destroy
  has_many :sites, :through => :community_sites
  
  #has_and_belongs_to_many 	:communities, :join_table => "community_neighbors", :class_name => "Community",
  #							:foreign_key => "a_community_id", :association_foreign_key => "b_community_id"
  has_many :community_neighbors
  has_many :neighbors, :through => :community_neighbors, :class_name => "Community", :foreign_key => "neighbor_id"
  
  
  analyzer = Ferret::Analysis::PerFieldAnalyzer.new(Ferret::Analysis::StandardAnalyzer.new)
  analyzer[:title] = Ferret::Analysis::RegExpAnalyzer.new(/./, false)
  analyzer[:position] = Ferret::Analysis::RegExpAnalyzer.new(/./, false)
  #acts_as_ferret({:fields => [ 'title', 'position' ]},
  #					{:analyzer=> analyzer})
  
  acts_as_ferret({:fields => {:title => {:store => :yes}, :position => {:store => :yes}}}, {:analyzer=> analyzer})
  
  cattr_reader :per_page
  @@per_page = 30
  
  def actually_neighbors
    query = ""
    query << "select *"
    query << " from communities INNER JOIN community_neighbors"
    query << " ON communities.id = community_neighbors.neighbor_id"
    query << " where (community_neighbors.community_id = '"
    query << self.id.to_s
    query << "' and community_neighbors.click_counts > 15) limit 15"
    communities = Community.find_by_sql [query]
    communities
  end
  
  def is_neighbor?(community)
    query = ""
    query << "select count(*)"
    query << " from communities INNER JOIN community_neighbors"
    query << " ON communities.id = community_neighbors.neighbor_id"
    query << " where (community_neighbors.community_id = '"
    query << self.id.to_s
    query << "' and community_neighbors.click_counts > 15)"
    Community.count_by_sql(query) > 0
    
  end
  
  def common_posts_by_community
    @posts = CommonPost.find(:all, :conditions => [ "community_id = ?",self.id], :order => "replied_at desc")
  end
  
  def can_edit?(user)
    return false if user.nil?
    user.community == self && user.scores > 5000 && Time.now.utc - user.join_community_at > 2592000 #30 days = 30*24*60*60 = 2592000 seconds
  end
  
  def before_save
    self.title = self.title.gsub(/^\<(script|frame)/i, '')
    self.description = self.description.gsub(/^\<(script|frame)/i, '')
  end
end
